<template>
  <el-dialog
    v-el-drag-dialog
    class="dialog-small upload-dialog"
    :append-to-body="appendToBody"
    :title="$t('媒体上传')"
    :visible="visible"
    :close-on-click-modal="false"
    width="900px"
    @close="()=>{$emit('close')}"
    @opened="loadRadioConfig"
    @update:visible="updateVisible">
    <el-form size="small" hide-required-asterisk inline>
      <el-form-item :label="$t('选择上传目录')">
        <el-select-tree
          width="386px"
          v-model="folderId"
          :placeholder="$t('请选择')"
          :data="treeData"
          :check-strictly="true"
          :props="{
            value: 'id',
            label: 'name',
            children: 'children'
          }"
          :ollie-disabled="true"
          :disabled-values="[-1]"
          @change="menuChange">
        </el-select-tree>
      </el-form-item>
      <el-form-item style="margin-left: 6px;" :label="$t('上传方式')">
        <el-radio-group v-model="uploadWay">
          <el-radio label="1">{{ $t('逐个') }}</el-radio>
          <el-radio label="2">{{ $t('同时') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="action-row">
      <el-upload
        action="#"
        multiple
        :show-file-list="false"
        :auto-upload="false"
        :file-list="uploadList"
        :on-change="fileChange">
        <el-button size="small" style="width: 110px;" type="primary">{{ $t('添加本地文件') }}</el-button>
      </el-upload>
      <el-button size="small" :disabled="disabledStart" class="ml-18" style="width: 110px;" type="primary" @click="startUpload">{{ $t('开始上传') }}</el-button>
      <el-select size="small" class="ml-18" style="width: 120px;" v-model="delType">
        <el-option
          v-for="op in delOpts"
          :key="op.value"
          :value="op.value"
          :label="$t(op.label)"></el-option>
      </el-select>
      <el-button size="small" class="ml-15" style="width: 60px;" type="primary" @click="delFile">{{ $t('删除') }}</el-button>
    </div>
    <div class="upload-info">
      <list
        ref="list"
        height="424px"
        :list-data="uploadList"
        :list-cols="listCols"
        :action-opts="actionOpts">
        <template slot="file_statusSlot" slot-scope="{row}">
          <bs-upload-progress
            :status="row.file_status"
            />
        </template>
        <template slot="menuSlot" slot-scope="{row}">
          {{ findFolderNameById(row.menu, treeData) }}
        </template>
        <template slot="sizeSlot" slot-scope="{row}">
          {{ row.size | getFileSize }}
        </template>
        <template slot="typeSlot" slot-scope="{row}">
          {{ row.name | getFileType }}
        </template>
        <template slot="actionSlot" slot-scope="{row}">
          <div v-if="row.file_status === 'wating' || typeof row.file_status === 'number'" class="action-slot">
            <template v-if="isPic(row.name)">
              <el-checkbox-group v-model="row.isConvert">
                <el-checkbox label="转码"></el-checkbox>
              </el-checkbox-group>
            </template>
            <!-- <div class="action-icon" v-if="typeof row.status === 'number'"><img src="./icon/stop.png" /></div>
            <div class="action-icon" v-else><img src="./icon/play.png" /></div> -->
            <div @click="delUpload({file: row})" class="action-icon"><img src="./icon/del.png" /></div>
          </div>
         
        </template>
      </list>

      <div class="total-info">
        <div class="total-info-text">
          <span class="total-info-text__label">{{ $t('总大小') }}</span>
          <div class="total-info-text__main">{{ totalSize | getFileSize }}</div>
        </div>
        <div class="total-info-text">
          <span class="total-info-text__label">{{ $t('速度') }}</span>
          <div class="total-info-text__main">{{ totalSpeed }}</div>
        </div>
        <div class="total-info-text">
          <span class="total-info-text__label">{{ $t('剩余时间') }}</span>
          <div class="total-info-text__main">{{ totalOverTime | s2Hms }}</div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import List from '@/components/List'
import MediaApi from '@/api/media.js'
import CommonApi from '@/api/common.js'
import {getFileSize} from '@/utils'
import { useCancelToken } from '@/utils/request'
import {createNamespacedHelpers} from 'vuex'
const { mapGetters, mapState, mapActions } = createNamespacedHelpers('media')

export default {
  filters: {
    getFileSize(size) {
      return getFileSize(size)
    },
    getFileType(fileName) {
      const fileNameSplit = fileName.split('.')
      return fileNameSplit[fileNameSplit.length - 1]
    },
    s2Hms(s) {
      if (!s && s !== 0) return ''
      let m = ~~(s / 60)
      if (m < 1) {
        return `00:00:${s > 9 ? s : '0' + s}`
      } else {
        s = s % 60
        const H = ~~(m / 60)
        if (H < 1) {
          return `00:${m > 9 ? m : '0' + m}:${s > 9 ? s : '0' + s}`
        } else {
          m = m % 60
          return `${H > 9 ? H : '0' + H}:${m > 9 ? m : '0' + m}:${s > 9 ? s : '0' + s}`
        }
      }
    }
  },
  components: {
    List
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    initFolderId: {
      type: [Number, String],
      default: 0
    },
    initUserId: {
      type: [Number, String],
      default: ''
    },
    appendToBody: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadWay: '1',
      delType: '',
      delOpts: [{
        label: '全部文件', value: ''
      }, {
        label: '上传成功文件', value: 'success'
      }, {
        label: '上传失败文件', value: 'fail'
      }],
      listCols: [
        { label: '文件名', prop: 'name' },
        { label: '目录', prop: 'menu', slot: true },
        { label: '大小', prop: 'size', slot: true },
        { label: '速度', prop: 'speed' },
        { label: '类型', prop: 'type', slot: true },
        { label: '状态', prop: 'file_status', slot: true, width: '130px' },
      ],
      actionOpts: {
        slot: true,
        show: true,
        hidEditBtn: true,
        hidDelBtn: true,
        align: 'center',
        name: '操作'
      },
      folderId: 0,
      ownerUserId: '',
      isConvert: false
    }
  },
  watch: {
    initFolderId: {
      immediate: true,
      handler(v) {
        this.folderId = v
      }
    },
    initUserId: {
      immediate: true,
      handler(v) {
        this.ownerUserId = v
      }
    },
    folderId: {
      immediate: true,
      handler(v) {
        if (v === -1 && this.visible) {
          // this.$alert('提示', '此目录不允许操作，已更换')
          this.$nextTick(() => this.folderId = 0)
        }
      }
    },
    uploadList: {
      deep: true,
      handler(v) {
        this.$nextTick(() => {
          this.$refs.list && this.$refs.list.$refs.list.doLayout()
        })
      }
    }
  },
  computed: {
    ...mapGetters(['menuTreeNoOther']),
    ...mapState(['uploadList', 'singleUploading']),
    treeData() {
      return this.everyAddId(this.menuTreeNoOther(1))
    },
    totalSize() {
      return this.uploadList.reduce((pv,item) => {
        return pv + item.size
      }, 0)
    },
    totalSpeed() {
      if (this.fetchingNum < 1) return ''
      const speedCont = this.uploadList.reduce((pv,item) => {
        if (!item.speed) return pv
        let _speed = Number(item.speed.replace('KB/S', ''))
        return pv + _speed
      }, 0)
      const avgSpeed = (speedCont / this.fetchingNum).toFixed('1')
      return `${avgSpeed}KB/S`
    },
    totalOverTime() { // 单位秒
      if (!this.totalSpeed) return ''
      if (this.uploadWay === '1') { // 逐个上传 取总大小除总速度
        const speed = Number(this.totalSpeed.replace('KB/S', ''))
        return Math.floor(this.totalSize / 1024 / speed)
      } else { // 同时上传取上传列表中剩余时间最大值
        let max = 0
        this.uploadList.forEach(item => {
          if (item.file_overTime && (item.file_overTime > max)) {
            max = item.file_overTime
          }
        })
        return max
      }
    },
    fetchingNum() {
      return this.uploadList.filter(item => {
        return typeof item.file_status === 'number'
      }).length
    },
    disabledStart() {
      return this.uploadList.some(item => typeof item.file_status === 'number') || this.singleUploading
    }
  },
  methods: {
    everyAddId(arr) {
      return arr.map(item => {
        let out = {}
        let children = []
        if (item.children && item.children instanceof Array && item.children.length > 0) {
          children = this.everyAddId(item.children)
        }
        out = {
          ...item
        }
        if (!out.id && out.id !== 0) {
          out.id = `0#${out.name}`
        }
        if (children.length > 0) out.children = children
        return out
      })
    },
    menuChange(v, data) {
      this.ownerUserId = data._isSub ? data.ownerUserId : ''
    },
    ...mapActions([
      'setUploadList',
      'singleUpload',
      'mutiUpload',
      'delUpload'
    ]),
    async loadRadioConfig() {
      const res = await CommonApi.loadDictionary({code: 'convert'})
      const jsonValue = res? res.jsonValue : null
      if(jsonValue) {
        this.isConvert = jsonValue.video
      }
    },
    // 判断是否是图片
    isPic(fileName) {
      const suportSuffix = [
        'PNG', 'BMP', 'JPG', 'TIF', 'GIF', 'JPEG'
      ]
      const fileNameSplit = fileName.split('.')
      const suffix = fileNameSplit[fileNameSplit.length - 1].toUpperCase()
      if (suportSuffix.indexOf(suffix) === -1) return true
      return false
    },
    findFolderNameById(folderId, tree) {
      for (let i = 0; i < tree.length; i++) {
        if (folderId === tree[i].id) {
          return tree[i].name
        } else if (tree[i].children && tree[i].children instanceof Array && tree[i].children.length > 0){
          const name = this.findFolderNameById(folderId, tree[i].children)
          if (name !== null) return name
          continue
        }
      }
      return null
    },
    updateVisible(v) {
      this.$emit('update:visible', v)
    },
    startUpload() {
      if (this.uploadWay === '1') {
        this.singleUpload()
      } else {
        this.mutiUpload()
      }
    },
    _valiFile(file) {
      const {size, name} = file
      // const over1G = (size / 1024 / 1024 / 1024) > 1
      const suportSuffix = [
        'AVI', 'MOV', 'MPG', 'MKV', 'MP4', 'VOB', 'TRP', 'TS', 'WMV', 'FLV',
        'PNG', 'BMP', 'JPG', 'TIF', 'GIF', 'JPEG',
        'DOC', 'DOCX', 'XLS', 'XLSX', 'PPT', 'PPTX', 'PDF',
        'MP3', 'WMA', 'AAC', 'WAV',
        'RSS', 'TXT'
      ]
      const fileNameSplit = name.split('.')
      const suffix = fileNameSplit[fileNameSplit.length - 1].toUpperCase()
      
      console.log(suffix)

      // if (over1G) return false
      if (suportSuffix.indexOf(suffix) === -1) return false

      return true
    },
    
    async fileChange(file, fileList) {

      if (!this._valiFile(file)) {
        fileList = fileList.filter(f => f.uid !== file.uid)
        console.log('filel', fileList)
      }

      console.log('-----filechange1----', file, fileList)

      // if (this.isVideooOrAudio(file.name)) {
        //视频需要判断时长
        // if (file.status !== 'ready') return
        // const res = await this.getVideoInfo(file)
        // if (parseInt(res.duration) %5 !== 0) {
        //     this.$message.error('时长不符合要求,请选择时长为5秒倍数的素材')
        //     this.setUploadList(fileList.filter(item => item.uid !== file.uid))
        // } else {
          this.setUploadList(fileList.map(item => {
            item.isConvert = this.isConvert
            return {
              ownerUserId: this.ownerUserId,
              menu: this.folderId,
              ...item
            }
          }))
        // }
      // } else {
        // this.setUploadList(fileList.map(item => {
        //   item.isConvert = this.isConvert
        //   return {
        //     ownerUserId: this.ownerUserId,
        //     menu: this.folderId,
        //     ...item
        //   }
        // }))
      // }

      // this.setUploadList(fileList.map(item => {
      //   item.isConvert = this.isConvert
      //   return {
      //     ownerUserId: this.ownerUserId,
      //     menu: this.folderId,
      //     ...item
      //   }
      // }))
    },
   getVideoInfo(file) {
      return new Promise((resolve) => {
          const videoElement = document.createElement("video");
          videoElement.src = URL.createObjectURL(file.raw);
          videoElement.addEventListener("loadedmetadata", function () {
              resolve({
                duration: videoElement.duration,
              });
          });
      });
    },
    isVideooOrAudio(fileName) {
				const suportSuffix = [
          'AVI', 'MOV', 'MPG', 'MKV', 'MP4', 'VOB', 'TRP', 'TS', 'WMV', 'FLV',
          'MP3', 'WMA', 'AAC', 'WAV'
        ]
				const fileNameSplit = fileName.split('.')
				const suffix = fileNameSplit[fileNameSplit.length - 1].toUpperCase()
				if (suportSuffix.indexOf(suffix) === -1) return false
				return true
    },
    delFile() {
      this.delUpload({fileState: this.delType})
    }
  },
}
</script>

<style lang="scss" scoped>

@mixin flex-row() {
  display: flex;
  align-items: center;
}

.upload-dialog {
  ::v-deep .el-dialog {
    height: 645px !important;
  }
  ::v-deep .el-dialog .el-dialog__body {
    padding-top: 20px !important;
  }
  .ml-18 {
    margin-left: 15px;
  }
  .ml-20 {
    margin-left: 15px;
  }
  .ml-22 {
    margin-left: 15px;
  }
  .ml-15 {
    margin-left: 15px;
  }
  .action-row {
    @include flex-row();
  }
  .upload-info {
    margin-top: 15px;

    .total-info {
      margin-top: 15px;
      @include flex-row();
      justify-content: space-between;

      &-text {
        font-size: 14px;
        color: #595959;
        @include flex-row();

        &__label {
          margin-right: 15px;
        }
        &__main {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 200px;
          height: 36px;
          line-height: 36px;
          color: #666;
          padding: 0 16px;
          border: 1px solid #E9E9E9;
        }
      }
    }
  }

  .action-slot {
    @include flex-row();
    justify-content: center;
    .action-icon + .action-icon {
      margin-left: 10px;
    }
  }
  .action-icon {
    display: flex;
    cursor: pointer;
    margin-left: 10px;
    img {
      width: 20px;
      height: 20px;
    }
  }
}
::v-deep .total-info-text__main{height: 30px !important;line-height: 30px !important;margin-top:5px;}

</style>